package com.weixin.paleituo.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.weixin.paleituo.R;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BasePersonActivity;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.bean.WithdrawAccountBean;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.LoadingPagerHead;

import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * 我的佣金提现界面
 * 目前只开通支付宝提现，微信提现暂未开通。
 *
 * @author fengzhen
 * @version v1.0, 2018/5/14
 */
public class BrokerageWithdrawActivity extends BasePersonActivity {

    public static final double MIN = 0.1;
    public static final double MAX = 50000;

    @BindView(R.id.rbtn_alipay_activity_brokerage_withdraw)
    RadioButton mRbtnAlipayActivityBrokerageWithdraw;
    @BindView(R.id.rbtn_wechat_activity_brokerage_withdraw)
    RadioButton mRbtnWechatActivityBrokerageWithdraw;
    @BindView(R.id.radiogroup_activity_brokerage_withdraw)
    RadioGroup mRadiogroupActivityBrokerageWithdraw;
    @BindView(R.id.ll_unopen_activity_brokerage_withdraw)
    LinearLayout mLlUnopenActivityBrokerageWithdraw;
    @BindView(R.id.et_name_activity_brokerage_withdraw)
    EditText mEtNameActivityBrokerageWithdraw;
    @BindView(R.id.et_account_activity_brokerage_withdraw)
    EditText mEtAccountActivityBrokerageWithdraw;
    @BindView(R.id.et_money_activity_brokerage_withdraw)
    EditText mEtMoneyActivityBrokerageWithdraw;
    @BindView(R.id.tv_balance_activity_brokerage_withdraw)
    TextView mTvBalanceActivityBrokerageWithdraw;
    @BindView(R.id.tv_getall_activity_brokerage_withdraw)
    TextView mTvGetallActivityBrokerageWithdraw;
    @BindView(R.id.btn_withdraw_activity_brokerage_withdraw)
    Button mBtnWithdrawActivityBrokerageWithdraw;
    @BindView(R.id.ll_usefull_activity_brokerage_withdraw)
    LinearLayout mLlUsefullActivityBrokerageWithdraw;

    private LoadingPagerHead mLoadingPagerHead;
    private WithdrawAccountBean mDataBean;
    // 提现类型 1：支付宝 2：微信
    private int mType = 1;
    private Dialog mLoadingDialog;

    public static Intent call2BrokerageWithdrawActivity(Context context) {
        Intent intent = new Intent(context, BrokerageWithdrawActivity.class);
        return intent;
    }

    @Override
    protected View getContentView(Context context) {
        mLoadingPagerHead = new LoadingPagerHead(this) {
            @Override
            protected void close() {
                onBackPressed();
            }

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(BrokerageWithdrawActivity.this,
                        R.layout.activity_brokerage_withdraw);
            }

            @Override
            protected void reLoading() {
                getData();
            }
        };
        return mLoadingPagerHead;
    }

    @Override
    protected void initData() {
        super.initData();
        mTvTitle.setText("提现");

        getData();
    }

    private void getData() {
        mLoadingPagerHead.showPagerView(Contans.STATE_LOADING);
        Observable<StatusCode<WithdrawAccountBean>> observable = ApiUtils.getApi().getAccountForWithdraw(BaseApplication.getToken(), BaseApplication.getUserId(),
                BaseApplication.sUserInfoBean.getUsername());
        HttpUtil.getInstance().toSubscribe(observable,
                new ProgressSubscriber<WithdrawAccountBean>(this) {
                    @Override
                    protected void _onNext(StatusCode<WithdrawAccountBean> statusCode) {
                        mLoadingPagerHead.showPagerView(Contans.STATE_SUCCEED);
                        mDataBean = statusCode.getData();

                        mRbtnAlipayActivityBrokerageWithdraw.setChecked(true);
                        mTvBalanceActivityBrokerageWithdraw.setText(String.format(
                                getString(R.string.s_balance), UIUtils.getMoney(mDataBean.getBalance())));
                    }

                    @Override
                    protected void _onError(String message) {
                        mLoadingPagerHead.showPagerView(Contans.STATE_ERROR);
                        ToastUtils.makeText(message);
                    }
                }, "", lifecycleSubject, false, true);
    }

    private void setUnopen(boolean open) {
        mLlUnopenActivityBrokerageWithdraw.setVisibility(open ? View.VISIBLE : View.GONE);
        mLlUsefullActivityBrokerageWithdraw.setVisibility(open ? View.GONE : View.VISIBLE);
    }

    @OnClick({R.id.tv_getall_activity_brokerage_withdraw, R.id.btn_withdraw_activity_brokerage_withdraw})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            /**
             * 全部提现
             */
            case R.id.tv_getall_activity_brokerage_withdraw:
                mEtMoneyActivityBrokerageWithdraw.setText(String.valueOf(mDataBean.getBalance()));
                break;

            /**
             * 提现
             */
            case R.id.btn_withdraw_activity_brokerage_withdraw:
                String name = mEtNameActivityBrokerageWithdraw.getText().toString();
                String account = mEtAccountActivityBrokerageWithdraw.getText().toString();
                String money = mEtMoneyActivityBrokerageWithdraw.getText().toString();
                if (checkInfo(name, account, money)) {
                    commit(name, account, money);
                }
                break;
        }
    }

    private boolean checkInfo(String name, String account, String money) {
        if (TextUtils.isEmpty(name)) {
            UIUtils.showCarToast(this, 1, "请输入您的姓名");
            return false;
        }
        if (TextUtils.isEmpty(account)) {
            UIUtils.showCarToast(this, 1, "请输入您的支付宝账号");
            return false;
        }
        if (TextUtils.isEmpty(money)) {
            UIUtils.showCarToast(this, 1, "请输入提现金额");
            return false;
        }
        double moneyD = 0.0;
        try {
            moneyD = Double.valueOf(money);
        } catch (Exception e) {
            UIUtils.showCarToast(this, 1, "请输入正确提现金额");
            return false;
        }
        if (moneyD < MIN) {
            UIUtils.showCarToast(this, 1, "单次提现最少0.1");
            return false;
        }
        if (moneyD > MAX) {
            UIUtils.showCarToast(this, 1, "单次提现最多50000");
            return false;
        }
        if (moneyD > mDataBean.getBalance()) {
            UIUtils.showCarToast(this, 1, "超出可提现余额");
            return false;
        }
        return true;
    }

    private void commit(String name, String account, String money) {
        if (mLoadingDialog == null) {
            mLoadingDialog = LoadingDialogUtils.createLoadingDialog(this, "");
        }
        mLoadingDialog.show();

        Observable<StatusCode<WithdrawAccountBean>> observable = ApiUtils.getApi().commitWithdrawal(
                BaseApplication.getToken(),
                BaseApplication.getUserId(),
                BaseApplication.sUserInfoBean.getUsername(),
                mType,
                name,
                account,
                UIUtils.getMoney(Double.valueOf(money))
        );
        HttpUtil.getInstance().toSubscribe(observable,
                new ProgressSubscriber(this) {
                    @Override
                    protected void _onNext(StatusCode statusCode) {
                        LoadingDialogUtils.closeDialog(mLoadingDialog);
                        startActivity(WithdrawSuccessActivity.call2WithdrawSuccessActivity(BrokerageWithdrawActivity.this));
                        onBackPressed();
                    }

                    @Override
                    protected void _onError(String message) {
                        LoadingDialogUtils.closeDialog(mLoadingDialog);
                        ToastUtils.makeText(message);
                    }
                }, "", lifecycleSubject, false, true);
    }

    @OnCheckedChanged({R.id.rbtn_alipay_activity_brokerage_withdraw, R.id.rbtn_wechat_activity_brokerage_withdraw})
    public void onCheckChanged(CompoundButton btn, boolean checked) {
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.bottom_line_greeen);
        if (checked) {
            switch (btn.getId()) {

                case R.id.rbtn_alipay_activity_brokerage_withdraw:
                    mType = 1;
                    drawable.setBounds(0, 0,
                            (int) (mRbtnAlipayActivityBrokerageWithdraw.getLayout().getLineWidth(0) + getResources().getDimensionPixelSize(R.dimen.dp_8)),
                            UIUtils.dip2px(2));
                    mRbtnAlipayActivityBrokerageWithdraw.setCompoundDrawables(null, null, null, drawable);
                    mRbtnWechatActivityBrokerageWithdraw.setCompoundDrawables(null, null, null, null);
                    setUnopen(false);
//                    setUnopen(mDataBean.getAlipay() == null);
                    if (mDataBean.getAlipay() != null) {
                        mEtNameActivityBrokerageWithdraw.setText(mDataBean.getAlipay().getPayeeRealName());
                        mEtAccountActivityBrokerageWithdraw.setText(mDataBean.getAlipay().getPayeeAccount());
                    }
                    break;

                case R.id.rbtn_wechat_activity_brokerage_withdraw:
                    mType = 2;
                    drawable.setBounds(0, 0,
                            (int) (mRbtnWechatActivityBrokerageWithdraw.getLayout().getLineWidth(0) + getResources().getDimensionPixelSize(R.dimen.dp_8)),
                            UIUtils.dip2px(2));
                    mRbtnWechatActivityBrokerageWithdraw.setCompoundDrawables(null, null, null, drawable);
                    mRbtnAlipayActivityBrokerageWithdraw.setCompoundDrawables(null, null, null, null);
                    setUnopen(true);
                    if (mDataBean.getWechat() != null) {
                        // TODO: 2018/5/14 初始化微信帐号
                        ToastUtils.makeText("初始化微信");
                    }
                    break;
            }
        }
    }
}
